package com.lujianfei.powerinput.ui.template.presenter;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;

import com.lujianfei.powerinput.ui.template.base.TemplateAddTypeContract;
import com.lujianfei.powerinput.utils.ConfigUtils;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.BiConsumer;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public class TemplateAddTypePresenter implements TemplateAddTypeContract.Presenter {
    private final TemplateAddTypeContract.View view;
    private List<ConfigUtils.ConfigEntity> configEntities;
    public TemplateAddTypePresenter(TemplateAddTypeContract.View view) {
        this.view = view;
    }

    @Override
    public void init() {
        configEntities = ConfigUtils.loadConfig();
        Observable.fromIterable(configEntities)
                .flatMap(new Function<ConfigUtils.ConfigEntity, ObservableSource<ConfigUtils.ConfigEntity>>() {
                    @Override
                    public ObservableSource<ConfigUtils.ConfigEntity> apply(ConfigUtils.ConfigEntity configEntity) {
                        return Observable.just(configEntity);
                    }
                }).map(new Function<ConfigUtils.ConfigEntity, String>() {
            @Override
            public String apply(ConfigUtils.ConfigEntity configEntity) {
                return configEntity.getName();
            }
        }).toList().subscribe(new BiConsumer<List<String>, Throwable>() {
            @Override
            public void accept(List<String> strings, Throwable throwable) throws Exception {
                view.updateList(strings);
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view2, int i, long l) {
        ConfigUtils.ConfigEntity configEntity = configEntities.get(i);
        Intent intent = new Intent();
        intent.putExtra("data",configEntity);
        view.currentActivity().setResult(Activity.RESULT_OK,intent);
        view.currentActivity().finish();
    }
}
